import md5 from "js-md5";
import CryptoJS from "crypto-js";

/**
 * 获取url参数
 */
export function getUrlVariables(url) {
  let data = {};
  const idx = url.indexOf("?");
  if (idx < 0) {
    return data;
  }
  const query = url.substring(idx + 1);
  const vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split("=");
    data[pair[0]] = decodeURIComponent(pair[1]);
  }
  return data;
}

// 搜集参数
export function collData(target, source) {
  let data = {};
  for (const key in target) {
    data[key] = target[key];
  }
  for (const key in source) {
    data[key] = source[key];
  }
  return data;
}

// 取出data所有参数并签名
// 取出data所有参数并签名
export function sign(ajaxCfg) {
  console.log(ajaxCfg);
  let res = {},
    url = ajaxCfg.url,
    urlData = getUrlVariables(url);
  const t = new Date().getTime();
  res.t = t;
  let data = collData(ajaxCfg.data, urlData);
  let arr = [];
  for (const k in data) {
    if (data[k] !== undefined && data[k] !== "") {
      arr.push(k);
    }
  }
  const arrSort = arr.sort();
  let encodeStr = "";
  let ciphertext = "";
  if (arr.length > 0) {
    ciphertext = arr[0] + "=" + data[arr[0]] + "&t=" + t;
  } else {
    ciphertext = "t=" + t;
  }
  ciphertext = md5(ciphertext);
  for (const e of arrSort) {
    encodeStr += "&" + e + "=" + data[e];
  }
  encodeStr = encodeStr.substr(1);
  encodeStr += "&t=" + t + "&ciphertext=" + ciphertext;
  res.sign = md5(encodeStr);
  ajaxCfg.headers = Object.assign({}, ajaxCfg.headers, res);
}

// AES加密函数
export function aesEncrypt(word, keyWord) {
  const key = CryptoJS.enc.Utf8.parse(keyWord);
  const srcs = CryptoJS.enc.Utf8.parse(word);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
}

// 判断终端
export function getOpenOS() {
  const ua = navigator.userAgent;
  return {
    isAndroid: ua.indexOf("Android") > -1 || ua.indexOf("Adr") > -1 //android终端
  };
}

// 向app传递人机校验成功的票据
export function sendCaptchaVerification(captchaVerification) {
  const os = getOpenOS();
  if (!os.isAndroid) {
    if (typeof window.webkit !== "undefined") {
      window.webkit.messageHandlers.sendCaptchaVerification.postMessage({
        captchaVerification: captchaVerification
      });
    }
  } else {
    return window.AppJsObj.sendCaptchaVerification(JSON.stringify(captchaVerification));
  }
}